package com.onairm.baselibrary.net.interceptor;

import com.onairm.baselibrary.net.CacheBean;
import com.onairm.baselibrary.net.CacheManager;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by bqy on 2018/4/23.
 */

public class CacheInteceptor implements Interceptor {

    private CacheManager cacheManager;
    private boolean isCache;
    private String url;

    public CacheInteceptor(boolean isCache, String url) {
        cacheManager = CacheManager.getInstance();
        this.isCache = isCache;
        this.url = url;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (isCache) {
            ResponseBody body = response.body();
            BufferedSource source = body.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = Charset.defaultCharset();
            MediaType mediaType = body.contentType();
            if (mediaType != null) {
                charset = mediaType.charset(charset);
            }
            String bodyString = buffer.clone().readString(charset);
            CacheBean cacheBean = cacheManager.queryCache(url);
            long time = System.currentTimeMillis();
            if (cacheBean == null) {
                cacheBean = new CacheBean();
                cacheBean.setKey(url);
                cacheBean.setCache(bodyString);
                cacheBean.setTime(time);
                cacheManager.saveCache(cacheBean);
            } else {
                cacheBean.setCache(bodyString);
                cacheBean.setTime(time);
                cacheManager.updateCache(cacheBean);
            }
         }
        return response;
    }
}
